﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Innova.Microfinanzas.BusinessEntities;
using Innova.FoundationFramework.DataTypes;
using Innova.Microfinanzas.BusinessEntities.SystemEnums;
using MyCommerce.Presentation.GeneralParameters.IViews;
using MyCommerce.Business.GeneralParameters;
using Innova.Microfinanzas.BusinessEntities.EnumClassifierTypes;

namespace MyCommerce.Presentation.GeneralParameters.Presenters
{
    public class CategoryFillPresenter
    {
        private ICategoryFill pViewToPresent;

        public CategoryFillPresenter(ICategoryFill vViewToPresent)
        {
            pViewToPresent = vViewToPresent;
            pViewToPresent.OnCancel += new EventHandler(pViewToPresent_OnCancel);
            pViewToPresent.OnLoadView += new GenericEventHandler<List<CategoryRelation>>(pViewToPresent_OnLoadView);
            pViewToPresent.OnSave += new EventHandler(pViewToPresent_OnSave);
        }

        private void pViewToPresent_OnSave(object sender, EventArgs e)
        {
            try
            {
                CategoryRelationManager vCategoryRelationManager = new CategoryRelationManager();
                vCategoryRelationManager.SaveCategoryRelation(pViewToPresent.Get());
                pViewToPresent.CloseAndSetResult(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void pViewToPresent_OnLoadView(object sender, GenericEventArgs<List<CategoryRelation>> e)
        {
            CommonClassifierManager vCommonClassifierManager = new CommonClassifierManager();
            
            //Cargamos los tipos no usados y los tipos ya seleccionados pa dicha categoria.
            List<Classifier> pColProductType = new List<Classifier>();
            if (e.EventData != null)
            {
                pViewToPresent.ColCategory = vCommonClassifierManager.GetClassifierByIDType((long)CommonClassifierTypes.ProductCategory);
                foreach (CategoryRelation item in e.EventData)
                {
                    pColProductType.Add(vCommonClassifierManager.GetClassifierByID(item.IdcProductType));
                }
            }
            else
            {
                pViewToPresent.ColCategory = vCommonClassifierManager.GetCategoryUnused();
            }
            pColProductType.AddRange(vCommonClassifierManager.GetProductTypeUnused());
            pViewToPresent.ColProductType = pColProductType;


            if (e.EventData != null)
                pViewToPresent.Set(e.EventData);
        }

        private void pViewToPresent_OnCancel(object sender, EventArgs e)
        {
            pViewToPresent.CloseAndSetResult(false);
        }
    }
}
